package top.ajun.mall.product.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import top.ajun.common.utils.PageUtils;
import top.ajun.common.utils.Query;
import top.ajun.mall.product.dao.SkuInfoDao;
import top.ajun.mall.product.entity.SkuInfoEntity;
import top.ajun.mall.product.service.SkuInfoService;

import java.math.BigDecimal;
import java.util.Map;

@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
            new Query<SkuInfoEntity>().getPage(params),
            Wrappers.query()
        );
        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfo) {
        this.save(skuInfo);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        LambdaQueryWrapper<SkuInfoEntity> wrapper = Wrappers.lambdaQuery();

        // 检索关键字
        String key = (String) params.get("key");
        if (StrUtil.isNotEmpty(key)) {
            wrapper.and(w -> w.eq(SkuInfoEntity::getSkuId, key).or().like(SkuInfoEntity::getSkuName, key));
        }

        // 三级分类id
        String catelogId = (String) params.get("catelogId");
        if (StrUtil.isNotEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            wrapper.eq(SkuInfoEntity::getCatalogId, catelogId);
        }

        // 品牌id 
        String brandId = (String) params.get("brandId");
        if (StrUtil.isNotEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            wrapper.eq(SkuInfoEntity::getBrandId, brandId);
        }

        // 最小价格(大于等于最小价格)
        String min = (String) params.get("min");
        if (StrUtil.isNotEmpty(min)) {
            wrapper.ge(SkuInfoEntity::getPrice, min);
        }

        // 最大价格(小于等于最大价格)
        String max = (String) params.get("max");
        if (StrUtil.isNotEmpty(max)) {
            try {
                BigDecimal decimal = new BigDecimal(max);
                if (decimal.compareTo(BigDecimal.ZERO) > 0) {
                    wrapper.le(SkuInfoEntity::getPrice, max);
                }
            } catch (Exception ignored) {
            }
        }

        IPage<SkuInfoEntity> page = this.page(new Query<SkuInfoEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }

}